const router = require('koa-router')()
const query = require("../db/mysql");

router.get('/adminqa',async (ctx,next)=>{
    try{
        let sql = 'SELECT * FROM qa'
        let data = await query(sql)
        // console.log(data)
        return ctx.body = {
            status:200,
            data:data
        }
    }catch(err){
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }
})

router.get('/oneqa',async function (ctx,next){
    try{
        const qId = ctx.query.qId
        let sql = `SELECT * FROM qa where qid = ?`
        let data = await query(sql,[qId])
        return ctx.body = {
            status:200,
            data:data,
            msg:''
        }
    }catch (err){
        console.error(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }
  })

router.post('/udqa',async (ctx,next)=>{
    try{
        const {'画作id: ':pId,'题目id: ':qId,'题目内容: ':qContext,'A选项: ':opA,'B选项: ':opB,'C选项: ':opC,'D选项: ':opD,'答案：':answer} = ctx.request.body
        console.log(pId,qId,qContext,opA,opB,opC,opD,answer,qId);
        console.log(ctx.request.body);
        let sql = 'UPDATE qa SET pId = ?,qId = ?,qContext = ?,opA = ?,opB = ?,opC = ?,opD = ?,answer = ? WHERE qId = ?'
        await query(sql,[pId,qId,qContext,opA,opB,opC,opD,answer,qId])
        return ctx.body = {
            status:200,
            msg:'update success'
        }
    }catch{err=>{
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }}
})

router.post('/adminqa',async (ctx,next)=>{
    try{
        const {'画作id: ':pId,'题目id: ':qId,'题目内容: ':qContext,'A选项: ':opA,'B选项: ':opB,'C选项: ':opC,'D选项: ':opD,'答案：':answer} = ctx.request.body
        let sql = 'INSERT INTO qa(pId,qId,qContext,opA,opB,opC,opD,answer) VALUES(?,?,?,?,?,?,?,?)'
        await query(sql,[pId,qId,qContext,opA,opB,opC,opD,answer])
        return ctx.body = {
            status:200,
            msg:'insert success'
        }
    }catch{err=>{
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }}
})

router.delete('/adminqa',async(ctx,next)=>{
    try{
        let sql = 'DELETE FROM qa WHERE pId=? AND qId = ?'
        await query(sql,[ctx.query.pId,ctx.query.qId])
        return ctx.body = {
            status:200,
            msg:'delete success'
        }
    }catch{err=>{
        console.log(err)
        return ctx.body = {
            status:500,
            msg:err
        }
    }}
})

module.exports = router